package work3.work3;

import work3.work1.Goods;

import java.util.ArrayList;
import java.util.Random;

public class WareHouse {
    ArrayList<Thread> list = new ArrayList<>();
    static Goods[] goods = new Goods[5];
    static Point[] points = new Point[7];//进货点5个0，2个2 0：进货，1：销售

    static {//初始化商品以及销售点和进货点
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            points[i] = new Point(String.valueOf(i), 1);
            goods[i] = new Goods(String.valueOf(i), random.nextInt(10) + 50);
        }
        for (int i = 5; i < 7; i++) {
            points[i] = new Point(String.valueOf(i), 0);
        }
    }

    public WareHouse() {
        long start = System.currentTimeMillis();
        while (true) {

            Thread seal = seal();
            seal.start();
            try {
                seal.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            long end = System.currentTimeMillis();
            if (end - start == (2 * 1000)) break;

        }


    }

     Thread add(int index) {
        Thread thread = new Thread(() -> {

            for (int i = 0; i < 5; i++) {
                if (goods[i].getName().equals(String.valueOf(i))&&goods[i].getNum()<=50) {
                    goods[i].add(20);
                }
                break;
            }

        });
        return thread;
    }

    synchronized Thread seal() {
        Thread thread = new Thread(() -> {
            Random random = new Random();
            int index = random.nextInt(2) + 5;//售卖的窗口
            int good1 = random.nextInt(5);//商品的编号
            int sealNum = random.nextInt(5) + 1;//销售数

            if (goods[good1].getNum() < 20) {
                add(good1).start();

            } else {
                goods[good1].seal(sealNum);
                System.out.println("销售点：" + index + "销售了" + good1 + " " + sealNum + "个;还剩：" + goods[good1].getNum());
            }


        });
        return thread;
    }

}
